//
//  EditAttributeVC.m
//  dyseller
//
//  Created by 红喇叭 on 2017/11/22.
//  Copyright © 2017年 红喇叭. All rights reserved.
//

#import "EditAttributeVC.h"
#import "UIButton+addIndex.h"
#import "UIButton+EnlargeTouchArea.h"

@interface EditAttributeVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>{
   // NSMutableArray *_goodsAttr;
    NSMutableArray *_natureArr;
    NSInteger topnum;
    CGPoint offsetP ;

}

@property(nonatomic,strong)UITableView *editTableView;

@end

@implementation EditAttributeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    topnum = 0;
    if(_goodsAttr.count<1){
        _goodsAttr = [NSMutableArray array];
         [self goodsInfoAttr:_goodsID];
    }else{
       _natureArr = [NSMutableArray arrayWithArray:_goodsAttr];
    }
     [self setNavTitle:@"编辑属性" titleColor:[UIColor blackColor] font:font17];
    self.editTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 20)];
   
    __weak typeof (self)weakself = self;
    [self.backBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        if(![self dataContrast]){
            [weakself backAction];
        }else{
            [weakself.navigationController popViewControllerAnimated:YES];
        }
    }];
    
    UIButton *savebtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [savebtn setTitle:@"保存" forState:0];
    [savebtn setTitleColor:kGrayColor forState:0];
    [savebtn addTarget:self action:@selector(saveFoodSelectCategory) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:savebtn];
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameDidChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

//比较数据源是否被改过
- (BOOL)dataContrast{
    NSString *str = [_goodsAttr componentsJoinedByString:@","];
    NSString *str1 = [ToolClass md5:str];
    NSString *ptr = [_natureArr componentsJoinedByString:@","];
    NSString *ptr1 = [ToolClass md5:ptr];
    return [str1 isEqualToString:ptr1];
}

-(void)saveFoodSelectCategory{
    [self.view endEditing:YES];
    if([self dataContrast]){
        [AlertUtils showToastWithMessage:@"您没有进行操作，不需要保存！" inView:self.view hideAfterDelay:2.0 beIndeter:NO];
    }else{
        [self getSelectSKU];
    }
    
}

- (void)backAction{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"是否保存修改的信息" preferredStyle:UIAlertControllerStyleAlert];
    __weak typeof (self)weakSelf = self;
    [alertController addAction:[UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf getSelectSKU];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

-(void)keyboardFrameDidChange:(NSNotification*)notice
{
    NSDictionary * userInfo = notice.userInfo;
    NSValue * endFrameValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect endFrame = endFrameValue.CGRectValue;
    NSLog(@"=====%f",endFrame.origin.y);
    NSLog(@"====%f",_editTableView.contentOffset.y);
    
    if(endFrame.origin.y<SCREEN_H && topnum==0){
        offsetP = _editTableView.contentOffset;
        _editTableView.contentOffset = CGPointMake(0, _editTableView.contentOffset.y+endFrame.size.height);
        topnum++;
    }else if(endFrame.origin.y == SCREEN_H && topnum==1){
        _editTableView.contentOffset = offsetP;
        topnum =0;
    }

    
    
}


//返回的时候先保存选的数据
- (void)getSelectSKU{
    [self.view endEditing:YES];
    NSMutableArray *saveArray = @[].mutableCopy;
    for (int i = 0; i<_goodsAttr.count; i++) {
        NSMutableDictionary *dic = ((NSMutableDictionary *)_goodsAttr[i]).mutableCopy;
        NSMutableArray *attr_value_Arr = ((NSArray*)dic[@"attr_value_arr"]).mutableCopy;
        NSMutableArray *new_value_Arr = @[].mutableCopy;
        for(int j = 0;j<attr_value_Arr.count;j++){
            NSMutableDictionary *attr_value_dic = ((NSDictionary *)attr_value_Arr[j]).mutableCopy;
            if([attr_value_dic[@"rowSelect"] isEqualToString:@"1"]){
                [new_value_Arr addObject:attr_value_dic];
                if([dic[@"is_main"] isEqualToString:@"1"]){
                    if( ((NSString*) attr_value_dic[@"goods_price"]).length < 1){
                        [AlertUtils showToastWithMessage:@"请填入主属性的价格！！" inView:self.view hideAfterDelay:2.0 beIndeter:NO];
                        return ;
                    }
                }
            }
        }
        if(new_value_Arr.count>0){
            dic[@"attr_value_arr"] = new_value_Arr;
            [saveArray addObject:dic];
        }
    }
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:_goodsAttr];
    [userDefaults setObject:data forKey:HLBPropertyListArray];
    _completeBlock(saveArray);
    [self.navigationController popViewControllerAnimated:YES];
    NSLog(@"%@",saveArray);
}

#pragma  mark ========懒加载========
- (UITableView *)editTableView{
    if(_editTableView == nil){
        _editTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H-NavigationHeight-TableSafe) style:UITableViewStyleGrouped];
        _editTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _editTableView.delegate = self;
        _editTableView.dataSource = self;
        _editTableView.estimatedSectionHeaderHeight = 0;
        _editTableView.estimatedRowHeight = 0;
        [_editTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"editCell"];
        [self.view addSubview:_editTableView];
    }
    return _editTableView;

}

//处理数据
- (void)disposeData:(UIButton*)btn{
    [self.view endEditing:YES];
    btn.selected = !btn.selected;
    for(int i = 0;i<_goodsAttr.count;i++){
        NSMutableDictionary *dic = ((NSDictionary *)_goodsAttr[i]).mutableCopy;
        if(i == btn.tag){
            [dic setObject:btn.selected?@"1":@"0" forKey:@"is_main"];
        }else{
            //加入组的标识
            [dic setObject:@"0" forKey:@"is_main"];
        }
//        NSMutableArray *attr_value_Arr = ((NSArray*)dic[@"attr_value_arr"]).mutableCopy;
//        for(int j = 0;j<attr_value_Arr.count;j++){
//            NSMutableDictionary *attr_value_dic = ((NSDictionary *)attr_value_Arr[j]).mutableCopy;
//            [attr_value_dic setObject:@"0" forKey:@"rowSelect"];
//
//            attr_value_Arr[j] = attr_value_dic;
//        }
//        [dic setObject:attr_value_Arr forKey:@"attr_value_arr"];
        _goodsAttr[i] = dic;
    }

    [_editTableView reloadData];
   // [_editTableView reloadSections:[NSIndexSet indexSetWithIndex:btn.tag] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)onlySelectAction:(UIButton *)btn{
    btn.selected = !btn.selected;
    for(int i = 0;i<_goodsAttr.count;i++){
        NSMutableDictionary *dic = ((NSDictionary *)_goodsAttr[i]).mutableCopy;
        NSMutableArray *attr_value_Arr = ((NSArray*)dic[@"attr_value_arr"]).mutableCopy;
        for(int j = 0;j<attr_value_Arr.count;j++){
            NSMutableDictionary *attr_value_dic = ((NSDictionary *)attr_value_Arr[j]).mutableCopy;
            if(btn.index.section == i && btn.index.row == j){
                [attr_value_dic setObject:btn.selected?@"1":@"0" forKey:@"rowSelect"];
            }
            attr_value_Arr[j] = attr_value_dic;
        }
        [dic setObject:attr_value_Arr forKey:@"attr_value_arr"];
        _goodsAttr[i] = dic;
    }
    
    [_editTableView reloadRowsAtIndexPaths:@[btn.index] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma  mark ========网络请求========
- (void)goodsInfoAttr:(NSString *)shopID{
    __weak typeof (self)weakself = self;
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Goods/goodsAttr" parameter:@{@"goods_id":shopID} successBlock:^(PPHttpRequest *request, id responseObj) {
       _goodsAttr =((NSMutableArray *)responseObj).mutableCopy;
        [weakself addIdentify];
        [_editTableView reloadData];
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
    }];
}

//往网络请求来的数据种插入标识字段
- (void)addIdentify{
    for(int i = 0;i<_goodsAttr.count;i++){
        NSMutableDictionary *dic = ((NSDictionary *)_goodsAttr[i]).mutableCopy;
        //加入组的标识
        [dic setObject:@"0" forKey:@"is_main"];
        NSMutableArray *attr_value_Arr = ((NSArray*)dic[@"attr_value_arr"]).mutableCopy;
        for(int j = 0;j<attr_value_Arr.count;j++){
            NSMutableDictionary *attr_value_dic = ((NSDictionary *)attr_value_Arr[j]).mutableCopy;
            [attr_value_dic setObject:@"0" forKey:@"rowSelect"];
            [attr_value_dic setObject:_goods_Price forKey:@"goods_price"];
            attr_value_Arr[j] = attr_value_dic;
        }
        [dic setObject:attr_value_Arr forKey:@"attr_value_arr"];
        _goodsAttr[i] = dic;
    }
    
    if(_goodsSKU.count>0){
        for(int i = 0;i<_goodsSKU.count;i++){
            NSDictionary *dic = _goodsSKU[i];
            for (int i1=0; i1<_goodsAttr.count; i1++) {
                NSMutableDictionary *dic1 = ((NSDictionary *)_goodsAttr[i1]).mutableCopy;
                if(dic[@"attr_name_id"] == dic1[@"attr_name_id"]){
                    dic1[@"is_main"] = dic[@"is_main"];
                    _goodsAttr[i1] = dic1;
                }
            }
            NSMutableArray *attr_value_Arr = ((NSArray*)dic[@"attr_value_arr"]).mutableCopy;
            for(int j=0;j<attr_value_Arr.count;j++){
                NSMutableDictionary *attr_value_dic = ((NSDictionary *)attr_value_Arr[j]).mutableCopy;
                for(int j1=0;j1<_goodsAttr.count;j1++){
                    NSMutableDictionary *dic1 = ((NSDictionary *)_goodsAttr[j1]).mutableCopy;
                    NSMutableArray *attr_value_Arr_1 = ((NSArray*)dic1[@"attr_value_arr"]).mutableCopy;
                    for(int a=0;a<attr_value_Arr_1.count;a++){
                         NSMutableDictionary *attr_dic = ((NSDictionary *)attr_value_Arr_1[a]).mutableCopy;
                        if(attr_value_dic[@"attr_value_id"] == attr_dic[@"attr_value_id"]){
                            [attr_dic setObject:@"1" forKey:@"rowSelect"];
                            [attr_dic setObject:attr_value_dic[@"goods_price"] forKey:@"goods_price"];
                            attr_value_Arr_1[a] = attr_dic;
                        }
                    }
                    dic1[@"attr_value_arr"] = attr_value_Arr_1;
                    _goodsAttr [j1] = dic1;
                }
            }
        }
    }
    _natureArr = [NSMutableArray arrayWithArray:_goodsAttr];
}

#pragma  mark ========UITableView 代理========

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _goodsAttr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSDictionary *dic = _goodsAttr[section];
    NSArray *dataArr = dic[@"attr_value_arr"];
    return dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic = _goodsAttr[indexPath.section];
    NSArray *dataArr = dic[@"attr_value_arr"];
    NSDictionary *dicdata = dataArr[indexPath.row];
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"editCell"];
    UIButton *selectbtn = [[UIButton alloc] init];
    [selectbtn setImage:[UIImage imageNamed:@"edit_Radio3_default_nor.png"] forState:UIControlStateNormal];
    [selectbtn setImage:[UIImage imageNamed:@"edit_Radio3_default_selected.png"] forState:UIControlStateSelected];
    selectbtn.index = indexPath;
    [selectbtn addTarget:self action:@selector(onlySelectAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:selectbtn];
    selectbtn.sd_layout.leftSpaceToView(cell.contentView, GETWITH(200)).widthIs(GETWITH(80)).heightEqualToWidth().centerYEqualToView(cell.contentView);
    //增大点击范围
    [selectbtn setEnlargeEdgeWithTop:0 right:20 bottom:0 left:10];

    UITextField *specificationTextfield = [[UITextField alloc] init];
    specificationTextfield.borderStyle = UITextBorderStyleRoundedRect;
    specificationTextfield.text = dicdata[@"attr_value"];
    specificationTextfield.textAlignment = NSTextAlignmentCenter;
    [cell.contentView addSubview:specificationTextfield];
    specificationTextfield.index = indexPath;
    specificationTextfield.delegate = self;
    specificationTextfield.font = font14;
    specificationTextfield.tag = indexPath.row + 1;
    specificationTextfield.returnKeyType = UIReturnKeyDone;
     specificationTextfield.sd_layout.leftSpaceToView(selectbtn, GETWITH(20)).widthIs(GETWITH(140)).heightIs(30).centerYEqualToView(cell.contentView);
    
    UITextField *priceTextfield = [[UITextField alloc] init];
    priceTextfield.borderStyle = UITextBorderStyleRoundedRect;
    priceTextfield.text = dicdata[@"goods_price"];
    priceTextfield.textAlignment = NSTextAlignmentCenter;
    priceTextfield.delegate = self;
    priceTextfield.font = font14;
    priceTextfield.index = indexPath;
    priceTextfield.returnKeyType = UIReturnKeyDone;
    priceTextfield.placeholder = @"请输入金额";
    [cell.contentView addSubview:priceTextfield];
    priceTextfield.sd_layout.rightSpaceToView(cell.contentView, GETWITH(60)).widthIs(GETWITH(240)).heightIs(30).centerYEqualToView(cell.contentView);
    if([dic[@"is_main"] isEqualToString:@"0"]){
        priceTextfield.hidden = YES;
      
    }else{
        priceTextfield.hidden = NO;
        
    }
    if([dicdata[@"rowSelect"] isEqualToString:@"0"]){
        selectbtn.selected = NO;
        priceTextfield.enabled = NO;
        specificationTextfield.enabled = NO;
    }else{
        priceTextfield.enabled = YES;
        selectbtn.selected = YES;
        specificationTextfield.enabled = YES;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    NSDictionary *dic = _goodsAttr[section];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 41)];
    view.backgroundColor = kWhiteColor;
    UIButton *addFoodClass = [[UIButton alloc] initWithFrame:CGRectMake(GETWITH(36),0, GETWITH(200), GETHEIGHT(40))];
    addFoodClass.centerY = view.centerY;
    addFoodClass.titleLabel.font = font15;
    addFoodClass.tag = section;
    [addFoodClass setTitle:dic[@"attr_name"] forState:0];
    [addFoodClass setImage:[UIImage imageNamed:@"edit_Radio4_default_nor.png"] forState:UIControlStateNormal];
    [addFoodClass setImage:[UIImage imageNamed:@"edit_Radio3_default_selected.png"] forState:UIControlStateSelected];
    [addFoodClass setTitleColor:UIColorFromRGB(0x323333) forState:0];
    addFoodClass.imageEdgeInsets = UIEdgeInsetsMake(0,-(addFoodClass.frame.size.width +addFoodClass.imageView.frame.size.width)/2.0f, 0, 0);
    addFoodClass.titleEdgeInsets = UIEdgeInsetsMake(0, 0,0,(addFoodClass.frame.size.width -addFoodClass.imageView.frame.size.width)/2.0f);
    [addFoodClass addTarget:self action:@selector(disposeData:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:addFoodClass];
    if([dic[@"is_main"] isEqualToString:@"0"]){
        
        addFoodClass.selected = NO;
    }else{
        
        addFoodClass.selected = YES;
    }

    UIView *lineV = [[UIView alloc] initWithFrame:CGRectMake(0, view.bottom-1, SCREEN_W, 0.5)];
    lineV.backgroundColor = kGrayColor;
    [view addSubview:lineV];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
   
    return [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 20)];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 20;
}

#pragma  mark ========UITextFieldDelegate========
- (void)textFieldDidEndEditing:(UITextField *)textField{
    NSLog(@"%ld===%ld === %ld",(long)textField.tag,textField.index.section,textField.index.row);
    [self updateAttr_value:textField.tag sectionData:textField.index titile:textField.text];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

//每次编辑完 往数据源里面写，修改数据源
- (void)updateAttr_value:(NSInteger )valueTag sectionData:(NSIndexPath *)indexpath titile:(NSString *)title{
    
    for(int i = 0;i<_goodsAttr.count;i++){
        NSMutableDictionary *dic = ((NSDictionary *)_goodsAttr[i]).mutableCopy;
        NSMutableArray *attr_value_Arr = ((NSArray*)dic[@"attr_value_arr"]).mutableCopy;
        for(int j = 0;j<attr_value_Arr.count;j++){
            NSMutableDictionary *attr_value_dic = ((NSDictionary *)attr_value_Arr[j]).mutableCopy;
            if(valueTag==0){//价格textfield的修改
                if(indexpath.section == i && indexpath.row == j){
                     [attr_value_dic setObject:title forKey:@"goods_price"];
                }
            }else{//属性textfield的修改
                if(indexpath.section == i && indexpath.row == j){
                    [attr_value_dic setObject:title forKey:@"attr_value"];
                }
            }
           
            attr_value_Arr[j] = attr_value_dic;
        }
        [dic setObject:attr_value_Arr forKey:@"attr_value_arr"];
        _goodsAttr[i] = dic;
    }

}

@end
